﻿using CoreShop.Model;
using CoreShop.Model.UI;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CoreShop.Library
{
    public class HttpHelper
    {

        /// <summary>	
        /// 写入日志文件	
        /// </summary>	
        /// <param name="input"></param>	
        public static void WriteApiUrl(string input)
        {
            return;
            try
            {
                string folder = Directory.GetCurrentDirectory() + "\\Log";
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                string file = folder + "\\api" + System.DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".txt";
                using (StreamWriter SW = File.AppendText(file))
                {
                    SW.Write(input);
                }
            }
            catch (Exception ex)
            {
            }
        }


        /// <summary>
        ///  发送请求参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="sign"></param>
        /// <param name="vendor_sn"></param>
        /// <returns></returns>
        public static string httpPost(string url, string body)
        {
            try
            {
                WriteApiUrl(url + "\n" + body);
                //发送数据
                HttpWebRequest request = null;
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] byte1 = encoding.GetBytes(body);
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Timeout = 60000;
                request.Method = "POST";
                request.ContentType = "application/json";
                request.ContentLength = byte1.Length;
                request.Headers.Add("X-Authorization", "true");
                request.Headers.Add("X-AuthorizationType", "POS_ACCOUNT_PASSWORD_LOGIN");
                Stream stream = request.GetRequestStream();
                stream.Write(byte1, 0, byte1.Length);
                stream.Close();
                //发送成功后接收返回的json信息
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string lcHtml = string.Empty;
                Encoding enc = Encoding.GetEncoding("UTF-8");
                Stream newStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(newStream, enc);
                lcHtml = streamReader.ReadToEnd();
                return lcHtml;
            }
            catch (Exception ex) { return ""; }
        }

        /// <summary>
        /// Post方法
        /// </summary>
        /// <param name="url">链接</param>
        /// <param name="param">参数，?xx=</param>
        /// <param name="timeout">超时时间</param>
        /// <returns></returns>
        public static ReturnModel PostSendMessage(string url, string param = "", string body = "{}", double timeout = 60.0, string authorizationType = "", sysuser sysUser = null)
        {
            ReturnModel returnModel = new ReturnModel() { Status = ReturnStatus.Success };

            try
            {
                using (HttpContent content = new StringContent(body, Encoding.UTF8))
                {
                    using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url + param))
                    {
                        using (HttpClient httpClient = new HttpClient())
                        {
                            httpClient.Timeout = TimeSpan.FromSeconds(timeout);

                            httpRequestMessage.Content = content;
                            httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                            if (!string.IsNullOrEmpty(authorizationType))
                            {
                                httpRequestMessage.Headers.Add("X-Authorization", "true");
                                httpRequestMessage.Headers.Add("X-AuthorizationType", authorizationType);
                            }
                            else if (sysUser != null)
                            {
                                httpRequestMessage.Headers.Add("X-Authorization", "true");
                                httpRequestMessage.Headers.Add("X-AuthorizationType", "MD5 Pos");
                                httpRequestMessage.Headers.Add("tenantId", sysUser.corpId.ToString());
                            }
                            if (sysUser != null)
                            {
                                httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", sysUser.ccessToken);
                            }
                                
                            returnModel.MessageOrString = httpClient.SendAsync(httpRequestMessage).Result.Content.ReadAsStringAsync().Result;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                returnModel.Status = ReturnStatus.Error;
                returnModel.MessageOrString = ex.Message;
            }

            return returnModel;
        }

        /// <summary>
        /// GET方法
        /// </summary>
        /// <param name="url">链接</param>
        /// <param name="param">参数，?xx=</param>
        /// <param name="timeout">超时时间</param>
        /// <returns></returns>
        public static ReturnModel GetSendMessage(string url, string param, double timeout = 30.0, sysuser sysUser = null)
        {
            ReturnModel returnModel = new ReturnModel()
            {
                Status = ReturnStatus.Success
            };

            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(timeout);

                    if (sysUser == null)
                    {
                        httpClient.DefaultRequestHeaders.Add("X-Authorization", "true");
                        httpClient.DefaultRequestHeaders.Add("X-AuthorizationType", "MD5 Pos");
                        httpClient.DefaultRequestHeaders.Add("tenantId", sysUser.corpId.ToString());
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer","");
                    }
                    else
                    {
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sysUser.ccessToken);
                    }
                    
                    returnModel.MessageOrString = httpClient.GetStringAsync(url + param).Result;
                }
            }
            catch (Exception ex)
            {
                returnModel.Status = ReturnStatus.Error;
                returnModel.MessageOrString = ex.Message;
            }

            return returnModel;
        }     


        /// <summary>
        ///  发送请求参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="sign"></param>
        /// <param name="vendor_sn"></param>
        /// <returns></returns>
        public static string httpPost(string url, string body, string accessToken)
        {
            try
            {
                WriteApiUrl(url + "\n" + body);

                Authorization a = null;
                //发送数据
                HttpWebRequest request = null;
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] byte1 = encoding.GetBytes(body);

                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Timeout = 60000;
                request.Method = "POST";
                //request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                request.ContentType = "application/json";
                request.ContentLength = byte1.Length;
                request.Headers.Add("Authorization", accessToken);
                Stream stream = request.GetRequestStream();
                stream.Write(byte1, 0, byte1.Length);
                stream.Close();
                //发送成功后接收返回的json信息 
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string lcHtml = string.Empty;
                Encoding enc = Encoding.GetEncoding("UTF-8");
                Stream newStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(newStream, enc);
                lcHtml = streamReader.ReadToEnd();
                return lcHtml;
            }
            catch { return null; }
        }

        /// <summary>
        ///  发送请求参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="sign"></param>
        /// <param name="vendor_sn"></param>
        /// <returns></returns>
        public static string httpGet(string url, string body, string accessToken)
        {
            WriteApiUrl(url + "\n" + body);
            Authorization a = null;
            //发送数据
            HttpWebRequest request = null;
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byte1 = encoding.GetBytes(body);

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 60000;
            request.Method = "POST";
            //request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byte1.Length;
            request.Headers.Add("Authorization", "Bearer " + accessToken);
            Stream stream = request.GetRequestStream();
            stream.Write(byte1, 0, byte1.Length);
            stream.Close();
            //发送成功后接收返回的json信息 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string lcHtml = string.Empty;
            Encoding enc = Encoding.GetEncoding("UTF-8");
            Stream newStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(newStream, enc);
            lcHtml = streamReader.ReadToEnd();
            return lcHtml;
        }


        public static async Task<string> httpPostFormData(string url, FormUrlEncodedContent body, string accessToken)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
                MultipartFormDataContent content = new MultipartFormDataContent();
                HttpResponseMessage response = await client.PostAsync(url, body);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else { return null; }
            }
            catch { return null; }
        }


        public static string httpGetString(string url, string accessToken)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.Timeout = TimeSpan.FromSeconds(30);
                httpClient.DefaultRequestHeaders.Add("Authorization", accessToken);
                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", accessToken);

                string rs = httpClient.GetStringAsync(url).Result;
                return rs;
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static ReturnModel DownloadFile(string url, double timeout = 60.0)
        {
            ReturnModel returnModel = new ReturnModel()
            {
                Status = ReturnStatus.Success
            };

            try
            {
                Uri uri = new Uri(url);
                //LogManager.WriteTxtLog($"下载图片url:{url}");
                using (HttpClient httpClient = new HttpClient())
                {
                    HttpResponseMessage result = httpClient.GetAsync(uri).Result;

                    if (!result.IsSuccessStatusCode)
                    {
                        returnModel.Status = ReturnStatus.Error;
                    }
                    else
                    {
                        returnModel.DataOrEntityData =
                            result.Content.ReadAsStreamAsync().Result;
                    }
                }
            }
            catch (Exception ex)
            {
                returnModel.Status = ReturnStatus.Error;
                returnModel.MessageOrString = ex.Message;
                LogManager.WriteTxtLog($"下载图片错误:{ex.Message}");
            }

            return returnModel;
        }


    }
}
